<?php
/**
 * Created by PhpStorm.
 * User: nefa
 * Date: 2018/2/23
 * Time: 上午10:00
 */


//全局变量
require_once 'conf/global.inc';
//开始方法
require_once 'core/core.inc';
//工具类函数
require_once 'core/function.inc';


_core_main();


//登录接口
function api_login(){
    $user = $_REQUEST['username'];
    $pass = $_REQUEST['password'];

    $data = array();
    $sql = "select * from user where username='".$user."'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }

    if (empty($data)){
        $str = array("code"=>"1","msg"=>"账号或密码错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }else{
        if ($pass === $data['password']){
            //验证是否启用
            if ($data['enable'] == 2){
                $str = array("code"=>"1","msg"=>"您的账号已停用,请联系管理员!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
                exit();
            }


            $repeat = array();
            $sql = "select * from session_data where userId='".$data['id']."'";
            $result = $GLOBALS['DB']->query($sql);
            while($res=$result->fetch()) {
                $repeat = $res;
            }
            if (!empty($repeat)){
                if ($repeat['sessionId'] !== session_id()){
                    $sql = "update session_data set sessionId='".session_id()."' where userId='".$data['id']."'";
                    $GLOBALS['DB']->query($sql);
                }
            }else{
                $sql = "insert into session_data values(null,'".$data['id']."','".session_id()."');";
                $GLOBALS['DB']->query($sql);
            }
            $str = array("code"=>"0","msg"=>"登录成功!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }else{
            $str = array("code"=>"1","msg"=>"账号或密码错误!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }

}


//获取验证码接口
function api_getVerificationCode(){
    $phone = $_REQUEST['phone'];

    if (empty($phone)){
        $str = array("code"=>"1","msg"=>"手机号码不能为空!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }
    $data = array();
    $sql = "select * from verificationcode where phone=".$phone;
    $result =  $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }

    $sendtime = date("Y-m-d H:i:s",time());
    $code = rand(10000000,99999999);
    //"{"info":{"successCount":1,"smsIds":["1521277277123_47765_9185_12791_zkm7qa$18691570864"]},"statusCode":200,"message":"请求成功","result":true}"
    if (empty($data)){
        //发送短信验证码
        $vars='{"%code%":"'.$code.'"}';
        $result=sendcloud_sendSMS($GLOBALS['smsUser'], $GLOBALS['smsKey'], $GLOBALS['smsTemplate_alarm'], $phone, $vars);
        $result = json_decode($result,true);
        if ($result['statusCode'] === 200){
            $sql = "insert into verificationcode values(null,'".$code."','".$phone."','".$sendtime."',null)";
            $res = $GLOBALS['DB']->query($sql);
            if ($res){
                $str = array("code"=>"0","msg"=>"短信已发送至:.$phone","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }else{
                $str = array("code"=>"1","msg"=>"未知错误,请重试!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }else{
            $str = array("code"=>"1","msg"=>"发送失败!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }else{
        //发送短信验证码
        $vars='{"%code%":"'.$code.'"}';
        $result=sendcloud_sendSMS($GLOBALS['smsUser'], $GLOBALS['smsKey'], $GLOBALS['smsTemplate_alarm'], $phone, $vars);
        $result = json_decode($result,true);
        if ($result['statusCode'] === 200){
            $sql = "update verificationcode set code='".$code."',sendtime='".$sendtime."' where phone='".$phone."'";
            $res = $GLOBALS['DB']->query($sql);
            if ($res){
                $str = array("code"=>"0","msg"=>"短信已发送至:.$phone","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }else{
                $str = array("code"=>"1","msg"=>"未知错误,请重试!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }else{
            $str = array("code"=>"1","msg"=>"发送失败!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }
    /*此处强制60秒内不会发送第二次(暂时不需要,不加)
     * else{
        $lasttime = $data[0]['sendtime'];

        $day = floor((strtotime($sendtime) - strtotime($lasttime))/86400);
        $hours = floor((strtotime($sendtime) - strtotime($lasttime))%86400/3600);
        $minute = floor((strtotime($sendtime) - strtotime($lasttime))%86400%3600/60);
        $second=floor((strtotime($sendtime)-strtotime($lasttime))%86400%60);

        if ($day != 0 || $hours != 0 || $minute != 0){
            $vars='{"%code%":"'.$code.'"}';
            $result=sendcloud_sendSMS($GLOBALS['smsUser'], $GLOBALS['smsKey'], $GLOBALS['smsTemplate_alarm'], $phone, $vars);
            $result = json_decode($result,true);
            if ($result['statusCode'] === 200){
                $sql = "update verificationcode set code='".$code."',sendtime='".$sendtime."'";
                $res = $GLOBALS['DB']->query($sql);
                if ($res){
                    $str = array("code"=>"0","msg"=>"短信已发送至:.$phone","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }else{
                    $str = array("code"=>"1","msg"=>"未知错误,请重试!","data"=>$sql);
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }
            }else{
                $str = array("code"=>"1","msg"=>"发送失败!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }else{
            if ($second < 59){
                $str = array("code"=>"1","msg"=>"发送间隔不满1分钟!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }else{
                $vars='{"%code%":"'.$code.'"}';
                $result=sendcloud_sendSMS($GLOBALS['smsUser'], $GLOBALS['smsKey'], $GLOBALS['smsTemplate_alarm'], $phone, $vars);
                $result = json_decode($result,true);
                if ($result['statusCode'] === 200){
                    $sql = "update verificationcode set code=".$code.",sendtime=".$sendtime;
                    $res = $GLOBALS['DB']->query($sql);
                    if ($res){
                        $str = array("code"=>"0","msg"=>"短信已发送至:.$phone","data"=>"");
                        echo json_encode($str,JSON_UNESCAPED_UNICODE);
                    }else{
                        $str = array("code"=>"1","msg"=>"未知错误,请重试!","data"=>"");
                        echo json_encode($str,JSON_UNESCAPED_UNICODE);
                    }
                }else{
                    $str = array("code"=>"1","msg"=>"发送失败!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }
            }
        }
    }*/
}

//验证码比对
function api_checkVerificationCode(){
    //取参
    $phone = $_REQUEST['phone'];
    $verification_code = $_REQUEST['verification_code'];
    //用前端发送过来的验证码和刚才获取到的验证码比对 暂留
    if (empty($phone) || empty($verification_code)){
        $str = array("code"=>"1","msg"=>"验证码错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    $sql = "select * from verificationcode where phone=".$phone;
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    $curenttime = date("Y-m-d H:i:s",time());
    if ($verification_code == $data['code']){
        //二次验证
        $day = floor((strtotime($curenttime) - strtotime($data['sendtime']))/86400);
        $hours = floor((strtotime($curenttime) - strtotime($data['sendtime']))%86400/3600);
        $minute = floor((strtotime($curenttime) - strtotime($data['sendtime']))%86400%3600/60);
        $second=floor((strtotime($curenttime)-strtotime($data['sendtime']))%86400%60);

        if ($day != 0 || $hours != 0 || $minute != 0){
            $str = array("code"=>"1","msg"=>"验证码已过期!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }else{
            if ($second < 59){
                $str = array("code"=>"0","msg"=>"验证通过!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }else{
                $str = array("code"=>"1","msg"=>"验证码已过期!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }
    }else{
        $str = array("code"=>"1","msg"=>"验证码错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//重置密码
function api_resetPass(){
    $phone = $_REQUEST['phone'];
    $verification_code = $_REQUEST['verification_code'];
    $newpass = $_REQUEST['newpass'];
    //
    //用前端发送过来的验证码和刚才获取到的验证码比对
    if (empty($phone) || empty($verification_code) || empty($newpass)){
        $str = array("code"=>"1","msg"=>"验证码错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    $sql = "select * from verificationcode where phone=".$phone;
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data = $res;
    }
    $curenttime = date("Y-m-d H:i:s",time());

    if ($verification_code === $data['code']){
        //二次验证
        $day = floor((strtotime($curenttime) - strtotime($data['sendtime']))/86400);
        $hours = floor((strtotime($curenttime) - strtotime($data['sendtime']))%86400/3600);
        $minute = floor((strtotime($curenttime) - strtotime($data['sendtime']))%86400%3600/60);

        if ($day != 0 || $hours != 0 ){
            $str = array("code"=>"1","msg"=>"验证码已过期!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }else{
            if ($minute < 11){
                //验证通过,进入
                $sql = "update user set password='".$newpass."' where phone=".$phone;
                $result = $GLOBALS['DB']->query($sql);
                if ($result){
                    $str = array("code"=>"0","msg"=>"重置成功!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }else{
                    $str = array("code"=>"0","msg"=>"重置失败,请稍后再试!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }
            }else{
                $str = array("code"=>"1","msg"=>"验证码已过期!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }
    }else{
        $str = array("code"=>"1","msg"=>"验证码错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//文件上传
function api_uploadFile(){
    $fileNames = $_REQUEST['info'];
    $names = '';
    if (empty($fileNames)){
        //为空
        $str = array("code"=>"0","msg"=>"参数为空");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }else{
        //不为空,获取到名称
        $names = array_diff(explode(',',$fileNames),['']);
    }
    //遍历
    $filePaths = array();
    foreach ($names as $name) {
        $fileData = $_FILES[$name];
        $file_name = $fileData['name'];
        $code = rand(10000,9999999);
        $file_name = date("Y-m-d",time()).time().'_'.$code.$file_name;
        $datetime = date("Y-m-d",time());
        $newFile = 'files/'.$file_name;
        //此函数会覆盖同名文件
        move_uploaded_file($fileData['tmp_name'],$newFile);
        //插入数据库文件表
        $sql = "insert into enclosure values(null,'".$newFile."','".$fileData['name']."','".$datetime."')";
        $result = $GLOBALS['DB']->query($sql);
        $fileid = $result->insertID();
        $file_id = array();
        $sql = "select id from enclosure where id=".$fileid;
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $file_id = $res;
        }
        $filePaths[] = $file_id;
    }
    $str = array("code"=>"0","msg"=>"上传成功","data"=>$filePaths);
    echo json_encode($str,JSON_UNESCAPED_UNICODE);
}

//获取我的提案数据
function api_getMyTiAnDataList(){
    if (!isset($_REQUEST['hashcode'])){
        //获取提案数据
        $curentPage = $_REQUEST['curentPage'];
        $mark = $_REQUEST['mark'];
        switch ($mark){
            case 'daifankui':
                $mark = 5;
                break;
            case 'shencha':
                $mark = 1;
                break;
            case 'jiaoban':
                $mark = 3;
                break;
            case 'banli':
                $mark = 4;
                break;
            case 'yiban':
                $mark = 6;
                break;
        }

        if (empty($curentPage) || empty($mark)){
            //返回响应
            $str = array("code"=>"1","msg"=>"参数不能为空!","data"=>'');
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
            exit();
        }

        $page = $curentPage-1;
        $perpage = 10;
        $data=array();

        //我的
        if ($mark === 'suoyou'){
            $sql="select * from proposal where userid=".$_SESSION['USERID']." or id in(select distinct proposalid from record where operateid=".$_SESSION['USERID'].") limit ".$page*$perpage.",".$perpage;
            $countsql = "select count(*) as num from proposal where userid=".$_SESSION['USERID']." or id in(select distinct proposalid from record where operateid=".$_SESSION['USERID'].")";
        }else{
            $sql="select * from proposal where userid=".$_SESSION['USERID']." and state =".$mark." or id in(select distinct proposalid from record where operateid=".$_SESSION['USERID'].") and state =".$mark."  limit ".$page*$perpage.",".$perpage;
            $countsql = "select count(*) as num from proposal where userid='".$_SESSION['USERID']."' and state =".$mark." or id in(select distinct proposalid from record where operateid=".$_SESSION['USERID'].") and state='".$mark."'";
        }
        //总数
        $result = $GLOBALS['DB']->query($countsql);
        if ($result){
            while($res=$result->fetch()) {
                $count = $res;
            }
        }

        $result=$GLOBALS['DB']->query($sql);
        if ($result){
            while($res=$result->fetch()) {
                $data[] = $res;
            }
        }
        $str = array("code"=>"0","msg"=>"获取成功!","size"=>$count['num'],"data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//搜索我的提案
function api_searchMyProposal(){
    if (!isset($_REQUEST['hashcode'])){
        //获取提案数据
        $curentPage = $_REQUEST['curentPage'];
        //关键字
        $keyword = $_REQUEST['keyword'];


        $page = $curentPage-1;
        $perpage = 10;
        $data=array();

        $sql="select * from proposal where (userid=".$_SESSION['USERID']." or id in(select distinct proposalid from record where operateid=".$_SESSION['USERID'].")) and (anyou like '%".$keyword."%') limit ".$page*$perpage.",".$perpage;
        $countsql="select count(*) as num from proposal where (userid=".$_SESSION['USERID']." or id in(select distinct proposalid from record where operateid=".$_SESSION['USERID'].")) and (anyou like '%".$keyword."%')";


        //总数
        $result = $GLOBALS['DB']->query($countsql);
        if ($result){
            while($res=$result->fetch()) {
                $count = $res;
            }
        }

        $result=$GLOBALS['DB']->query($sql);
        if ($result){
            while($res=$result->fetch()) {
                $data[] = $res;
            }
        }

        $str = array("code"=>"0","msg"=>"获取成功!","size"=>$count['num'],"data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//搜索委员信息
function api_searchWeiyuan(){
    $curentPage = $_REQUEST['curentPage'];
    $keyword = $_REQUEST['keyword'];

    $page = $curentPage-1;
    $perpage = 10;
    $data=array();
    $count = array();
    $sql = "select * from user where realname like '%".$keyword."%' limit ".$page*$perpage.",".$perpage;
    $countsql = "select count(*) as num from user where realname like '%".$keyword."%'";
    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }

    $result = $GLOBALS['DB']->query($countsql);
    while($res=$result->fetch()) {
        $count = $res;
    }

    $str = array("code"=>"0","msg"=>"获取成功!","size"=>$count['num'],"data"=>$data);
    echo json_encode($str,JSON_UNESCAPED_UNICODE);
}


//获取提案数据
function api_getTianDataList(){
    //获取提案数据
    $curentPage = $_REQUEST['curentPage'];
    $mark = $_REQUEST['mark'];

    switch ($mark){
        case 'daifankui':
            $mark = 5;
            break;
        case 'shencha':
            $mark = 1;
            break;
        case 'jiaoban':
            $mark = 3;
            break;
        case 'banli':
            $mark = 4;
            break;
        case 'yiban':
            $mark = 6;
            break;
    }

    if (empty($curentPage) || empty($mark)){
        //返回响应
        $str = array("code"=>"1","msg"=>"参数不能为空!","data"=>'');
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    $page = $curentPage-1;
    $perpage = 10;
    $data=array();
    if ($mark === 'wode'){
        if (empty($_SESSION['USERID'])){
            $str = array("code"=>"1","msg"=>"获取失败!","data"=>'');
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
            exit();
        }else{
            //我的
            $sql="select * from proposal where userid=".$_SESSION['USERID']." order by id desc limit ".$page*$perpage.",".$perpage;
            //总数
            $countsql = "select count(*) as num from proposal where userid='".$_SESSION['USERID']."'";
            $result = $GLOBALS['DB']->query($countsql);
            if ($result){
                while($res=$result->fetch()) {
                    $count = $res;
                }
            }
        }
    }
    else if ($mark === 'suoyou'){
        //所有
        $sql="select a.*,l.realname from proposal as a left join user as l on a.userid=l.id order by id desc limit ".$page*$perpage.",".$perpage;
        //总数
        $countsql = 'select count(*) as num from proposal';
        $result = $GLOBALS['DB']->query($countsql);
        if ($result){
            while($res=$result->fetch()) {
                $count = $res;
            }
        }
    }
    else{
        $sql="select * from proposal where state =".$mark." order by id desc limit ".$page*$perpage.",".$perpage;
        //总数
        $countsql = 'select count(*) as num from proposal where state='.$mark;
        $result = $GLOBALS['DB']->query($countsql);
        if ($result){
            while($res=$result->fetch()) {
                $count = $res;
            }
        }
    }
    $result=$GLOBALS['DB']->query($sql);
    if ($result){
        while($res=$result->fetch()) {
            $data[] = $res;
        }
    }
    $str = array("code"=>"0","msg"=>"获取成功!","size"=>$count['num'],"data"=>$data);
    echo json_encode($str,JSON_UNESCAPED_UNICODE);
}

function api_getAllTianDataList(){
    $curentPage = $_REQUEST['curentPage'];
    $mark = $_REQUEST['mark'];

    switch ($mark){
        case 'daifankui':
            $mark = 5;
            break;
        case 'shencha':
            $mark = 1;
            break;
        case 'jiaoban':
            $mark = 3;
            break;
        case 'banli':
            $mark = 4;
            break;
        case 'yiban':
            $mark = 6;
            break;
    }


    if (empty($curentPage) || empty($mark)){
        //返回响应
        $str = array("code"=>"1","msg"=>"参数不能为空!","data"=>'');
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    $page = $curentPage-1;
    $perpage = 10;
    $data=array();

    if ($mark === 'suoyou'){
        $sql="select a.*,l.realname from proposal as a left join user as l on a.userid=l.id order by id desc limit ".$page*$perpage.",".$perpage;
        //总数
        $countsql = 'select count(*) as num from proposal';
    }else{
        $sql="select a.*,l.realname from proposal as a left join user as l on a.userid=l.id where state=".$mark."  order by id desc limit ".$page*$perpage.",".$perpage;
        $countsql='select count(*) as num from proposal where state='.$mark;
    }

    $result = $GLOBALS['DB']->query($countsql);
    if ($result){
        while($res=$result->fetch()) {
            $count = $res;
        }
    }

    $result=$GLOBALS['DB']->query($sql);
    if ($result){
        while($res=$result->fetch()) {
            $data[] = $res;
        }
    }
    $str = array("code"=>"0","msg"=>"获取成功!","size"=>$count['num'],"data"=>$data);
    echo json_encode($str,JSON_UNESCAPED_UNICODE);
}

function api_searchProposal(){
    if (!isset($_REQUEST['keyword_search']) && !isset($_REQUEST['anyou_search'])){
        $str = array("code"=>"1","msg"=>"请填写搜索条件!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $keyword_search = $_REQUEST['keyword_search'];
        $anyou_search = $_REQUEST['anyou_search'];
        !isset($_REQUEST['curentPage'])? $curentPage=1:$curentPage=$_REQUEST['curentPage'];
        $page = $curentPage-1;
        $perpage = 10;
        $data = array();
        if ((isset($keyword_search) && isset($anyou_search))){
            $sql="select a.*,l.realname from proposal as a left join user as l on a.userid=l.id where realname like '%".$keyword_search."%' and anyou like '%".$anyou_search."%' order by id desc limit ".$page*$perpage.",".$perpage;
            $sql2="select count(*) as num from proposal as a left join user as l on a.userid=l.id where realname like '%".$keyword_search."%' and anyou like '%".$anyou_search."%'";
        }else{
            !empty($keyword_search)? $sql = "select a.*,l.realname from proposal as a left join user as l on a.userid=l.id where realname like '%".$keyword_search."%' order by id desc limit ".$page*$perpage.",".$perpage:$sql = "select a.*,l.realname from proposal as a left join user as l on a.userid=l.id where anyou like '%".$anyou_search."%' order by id desc limit ".$page*$perpage.",".$perpage;
            !empty($keyword_search)? $sql2 = "select count(*) as num from proposal as a left join user as l on a.userid=l.id where realname like '%".$keyword_search."%'" :$sql = "select count(*) as num from proposal as a left join user as l on a.userid=l.id where anyou like '%".$anyou_search."%'";
        }

        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $data[] = $res;
        }

        $count = array();
        $result = $GLOBALS['DB']->query($sql2);
        while($res=$result->fetch()) {
            $count = $res;
        }
        $str = array("code"=>"0","msg"=>"获取成功!","size"=>$count['num'],"data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}


function api_searchProposalToanyou(){
    if (!isset($_REQUEST['anyou_search'])){
        $str = array("code"=>"1","msg"=>"请填写搜索条件!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $anyou_search = $_REQUEST['anyou_search'];
        $mark = $_REQUEST['mark'];
        switch ($mark){
            case 'daifankui':
                $mark = 5;
                break;
            case 'shencha':
                $mark = 1;
                break;
            case 'jiaoban':
                $mark = 3;
                break;
            case 'banli':
                $mark = 4;
                break;
            case 'yiban':
                $mark = 6;
                break;
        }
        !isset($_REQUEST['curentPage'])? $curentPage=1:$curentPage=$_REQUEST['curentPage'];
        $page = $curentPage-1;
        $perpage = 10;
        $data = array();
        $sql = "select a.*,l.realname from proposal as a left join user as l on a.userid=l.id where anyou like '%".$anyou_search."%' and state=".$mark." order by id desc limit ".$page*$perpage.",".$perpage;
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $data[] = $res;
        }
        $count = array();
        $sql = "select count(*) as num from proposal as a left join user as l on a.userid=l.id where anyou like '%".$anyou_search."%' and state=".$mark;
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $count = $res;
        }
        $str = array("code"=>"0","msg"=>"获取成功!","size"=>$count['num'],"data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

function api_searchSponsor(){
    if (!empty($_REQUEST['keyword'])){
        $data = array();
        $sql = "select * from sponsor_unit where unitname like '%".$_REQUEST['keyword']."%'";
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $data[] = $res;
        }
        $str = array("code"=>"0","msg"=>"获取成功!","data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $str = array("code"=>"1","msg"=>"请填写搜索条件!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

function api_searchAssist(){
    if (!empty($_REQUEST['keyword'])){
        $data = array();
        $sql = "select * from assist_unit where unitname like '%".$_REQUEST['keyword']."%'";
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $data[] = $res;
        }

        $str = array("code"=>"0","msg"=>"获取成功!","data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $str = array("code"=>"1","msg"=>"请填写搜索条件!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//新建提案
function api_createProposal(){
    //用户id
    $userid = $_REQUEST['userId'];
    //提案人
    $tianren = $_REQUEST['tianren'];
    //附议人
    $fuyiren = $_REQUEST['fuyiren'];
    //提案内容
    $tianneirong = $_REQUEST['tianneirong'];
    //提案建议
    $tianjianyi = $_REQUEST['tianjianyi'];
    //案由
    $anyou = $_REQUEST['anyou'];
    //提案类型
    $tiantype = $_REQUEST['tiantype'];
    //届次
    $jieci = $_REQUEST['jieci'];
    //当前时间
    $commitTime = date("Y-m-d H:i:s",time());

    if (empty($fuyiren)){
        $fuyiren = '无';
    }

    //非空验证
    if (empty($tianren) || empty($tianneirong) || empty($tianjianyi) || empty($anyou) || empty($tiantype) || empty($jieci) || empty($userid)){
        $str = array("code"=>"1","msg"=>"所有带*的参数都必须填写!","data"=>'');
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        if (!empty($_REQUEST['fileid'])){
            $enclosureid = $_REQUEST['fileid'];
        }
        //$userid = 2;//这里需要查询时哪个用户提交的,并查出userid
        //这里存储所有信息到提案表
        if (empty($enclosureid)){
            $sql = "insert into proposal values(null,'".$userid."','1','".$commitTime."','0','0','2','".$commitTime."','".$anyou."','".$tiantype."','".$tianneirong."','".$tianjianyi."','0','".$jieci."','".$fuyiren."');";
        }else{
            $sql = "insert into proposal values(null,'".$userid."','1','".$commitTime."','0','0','2','".$commitTime."','".$anyou."','".$tiantype."','".$tianneirong."','".$tianjianyi."','".$enclosureid."','".$jieci."','".$fuyiren."');";
        }


        $result=$GLOBALS['DB']->query($sql);
        $proposalid =  $result->insertId();

        //插入提案记录
        $sql = "insert into record values(null,'".$commitTime."','".$tianren."','1','0分钟','无','暂留',".$proposalid.",'".$userid."')";
        $result = $GLOBALS['DB']->query($sql);

        //返回响应
        if ($result){
            $result = array("createTime"=>$commitTime,'anyou'=>$anyou);
            $str = array("code"=>"0","msg"=>"创建成功!","data"=>$result);
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
            $action='shencha';
        }else{
            $str = array("code"=>"1","msg"=>"创建失败!","data"=>'');
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }
}


//审查提案
function api_updateProposalState(){
    /**
     *  id 主键id
        operatetime 操作时间
        operatename 操作人
        operatetype 操作类型
        processtime 耗时
        remarks 备注
        info 详情
        proposalid 提案id
     */

    //提案id
    $proposalid =  $_REQUEST['proposalid'];
    //详情
    //是不是重点提案
    $isZhongdian = $_REQUEST['isZhongdian'];
    //承办单位
    $chengbandanwei = $_REQUEST['chengbandanwei'];
    $userid = $_REQUEST['userid'];
    //备注
    $remarks =  $_REQUEST['remarks'];
    //操作类型
    $operatetype =  $_REQUEST['operatetype'];//暂定  1:立案  2:不立案
    //操作时间
    $operatetime = date("Y-m-d H:i:s",time());


    if (empty($proposalid) || empty($remarks) || empty($operatetype) || empty($operatetime)  ){
        $str = array("code"=>"1","msg"=>"参数格式错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    //更新状态
    switch ($operatetype){
        case 1:
            //通过提案 -> 3.待交办
            $state = 3;
            $recordState = 2;

            //验证重点提案 1为是重点 2为不是重点
            if (empty($isZhongdian)){
                $str = array("code"=>"1","msg"=>"必须选择是不是重点提案!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
                exit();
            }


            //验证承办单位
            $sponsorData = getAllSponsorUnit();
            foreach ($sponsorData as $value){
                if ($chengbandanwei === $value['unitname']){
                    //如果有则取出id
                    $sponsor = $value['id'];
                }
            }

            if (empty($sponsor)){
                $str = array("code"=>"1","msg"=>"没有找到这个承办单位!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
                exit();
            }

            //更新提案表中承办单位
            $sql = "update proposal set sponsor='".$sponsor."',state='".$state."',stress='".$isZhongdian."' where id=".$proposalid."";
            $result = $GLOBALS['DB']->query($sql);

            if (!$result){
                $str = array("code"=>"1","msg"=>"没有找到这个提案!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
                exit();
            }

            $proposalData = getProposalInfo($proposalid);
            $message = "您的《".$proposalData['anyou']."》提案审查已通过!";

            break;
        case 2:
            //驳回提案 -> 2.未立案   不更新承办单位
            $state = 2;
            $recordState = 3;

            //更新提案表状态
            $sql = "update proposal set state='".$state."' where id=".$proposalid."";
            $result = $GLOBALS['DB']->query($sql);

            if (!$result){
                $str = array("code"=>"1","msg"=>"没有找到这个提案!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
                exit();
            }

            $proposalData = getProposalInfo($proposalid);
            $message = "您的《".$proposalData['anyou']."》提案审查未通过!";
            break;
    }

    $data = getUserInfo($userid);
    if (empty($data)){
        $str = array("code"=>"1","msg"=>"没有找到这个用户!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    $result = updateRecord($proposalid,$userid,$recordState,$remarks);
    if ($result){
        $str = array("code"=>"0","msg"=>"操作成功!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);

        $operatetype == 1 ? $action='jiaoban':$action='suoyou';
        //updateFixedTask($action);
        sendTask($message,$proposalData['userid'],$proposalid,$action,2,0);
    }else{
        $str = array("code"=>"1","msg"=>"操作失败!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//交办提案
function api_updateProposalStateToJiaoBan(){
    $zhuban = $_REQUEST['zhuban'];
    $xieban = $_REQUEST['xieban'];
    $proposalId = $_REQUEST['proposalId'];
    $userId = $_REQUEST['userId'];


    //查询主办和协办单位是否存在
    $sponsorData =  getAllSponsorUnit();//获取所有主办单位
    foreach ($sponsorData as $value){
        if ($zhuban === $value['unitname']){
            $sponsorId = $value['id'];
        }
    }

    if (empty($sponsorId)){
        $str = array("code"=>"1","msg"=>"没有这个主办单位,请修改后重试!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    if (!empty($xieban)){
        //$assisData =  getAllAssisUnit();//获取所有协办单位
        $assisData =  getAllSponsorUnit();//获取所有协办单位
        foreach ($assisData as $value){
            if ($xieban === $value['unitname']){
                $assisId = $value['id'];
            }
        }

        if (empty($assisId)){
            $str = array("code"=>"1","msg"=>"没有这个协办单位,请修改后重试!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
            exit();
        }

        //更新主办和协办单位
        $sql = "update proposal set sponsor='".$sponsorId."',assist='".$assisId."',state='4' where id='".$proposalId."'";
        $result = $GLOBALS['DB']->query($sql);



        if ($result){
            //更新记录
            $result = updateRecord($proposalId,$userId,'4','');
            if ($result){
                $str = array("code"=>"0","msg"=>"提交成功!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);

                $proposalData = getProposalInfo($proposalId);
                $action = 'banli';
                $message = "您的《".$proposalData['anyou']."》提案已交办!";
                sendTask($message,$proposalData['userid'],$proposalId,$action,2,0);
                //updateFixedTask($action);
            }else{
                $str = array("code"=>"1","msg"=>"提交失败,请联系系统管理员!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }else{
            $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
        exit();
    }

    //更新主办
    $sql = "update proposal set sponsor='".$sponsorId."',state='4' where id='".$proposalId."'";
    $result = $GLOBALS['DB']->query($sql);

    if ($result){
        //更新记录
        $result = updateRecord($proposalId,$userId,'4','');
        if ($result){
            $str = array("code"=>"0","msg"=>"提交成功!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);

            $proposalData = getProposalInfo($proposalId);
            $action = 'banli';
            $message = "您的《".$proposalData['anyou']."》提案已交办!";
            sendTask($message,$proposalData['userid'],$proposalId,$action,2,0);
            //updateFixedTask($action);
        }else{
            $str = array("code"=>"1","msg"=>"提交失败,请联系系统管理员!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }else{
        $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}


//提案签收
function api_proposalReceive(){
   $userId =  $_REQUEST['userId'];
   $proposalId =  $_REQUEST['proposalId'];
   $isbanli =  $_REQUEST['isbanli'];// 1办理   2.不办理
   $yuanyin =  $_REQUEST['yuanyin'];

    if (empty($proposalId) || empty($userId)|| empty($isbanli)){
        $str = array("code"=>"1","msg"=>"参数错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }

    switch ($isbanli){
       case '1'://确认办理->>状态6
           $state = '6';
           break;
       case '2'://不办理->>状态7
           $state = '7';
           //不办理->>待交办
           $sql = "update proposal set state='3' where id=".$proposalId;
           $GLOBALS['DB']->query($sql);
           break;
    }
    //插入更改记录
    $result = updateRecord($proposalId,$userId,$state,$yuanyin);
    if ($result){
        $str = array("code"=>"0","msg"=>"提交成功!","data"=>$proposalId);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);

        $proposalData = getProposalInfo($proposalId);
        $state === '6' ? $message = "您的《".$proposalData['anyou']."》提案已签收!":$message = "您的《".$proposalData['anyou']."》提案未签收!";
        $state === '6' ? $action = 'banli' : $action = 'jiaoban';
        sendTask($message,$proposalData['userid'],$proposalId,$action,2,0);
        //updateFixedTask($action);
    }else{
        $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}


//提案答复
function api_response(){
    $userid = $_REQUEST['userId'];
    $proposalId = $_REQUEST['proposalId'];
    $dafu = $_REQUEST['dafu'];//答复内容
    $fileid = $_REQUEST['fileId'];//文件id

    if (empty($dafu) || empty($fileid)|| empty($userid)|| empty($proposalId)){
        $str = array("code"=>"1","msg"=>"答复内容和文件都必填!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
    //更新提案状态为待反馈 状态5
    $proposalData = getProposalInfo($proposalId);

    if (empty($proposalData['enclosureid'])){
        //直接插入
        $sql = "update proposal set enclosureid='".$fileid."',state='5' where id=".$proposalId;
        error_log('插入文件信息!!->>'.$sql);

    }else{
        $newFileId = $proposalData['enclosureid'].','.$fileid;
        $sql = "update proposal set enclosureid='".$newFileId."',state='5' where id=".$proposalId;
        error_log('更新文件信息!!->>'.$sql);
    }
    $result = $GLOBALS['DB']->query($sql);
    if ($result){
        //提案表更新完毕,插入操作记录 8
        $result = updateRecord($proposalId,$userid,'8',$dafu);
        $data = getProposalRecordToLast($proposalId);
        $data['proposalName'] = $proposalData['anyou'];
        if ($result){
            $str = array("code"=>"0","msg"=>"提交成功!","data"=>$data);
            echo json_encode($str,JSON_UNESCAPED_UNICODE);

            $proposalData = getProposalInfo($proposalId);
            $message = "您的《".$proposalData['anyou']."》提案待反馈!";
            $action = 'daifankui';
            sendTask($message,$proposalData['userid'],$proposalId,$action,2,0);
           // updateFixedTask($action);
        }else{
            //数据库错误
            $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }else{
        //数据库错误
        $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

/*//修改密码
function api_changePwd(){
    $userId =  $_REQUEST['userId'];
    $password =  $_REQUEST['password'];

    if (empty($password) || empty($userId)){
        $str = array("code"=>"1","msg"=>"参数错误!","data"=>"{}");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        return;
    }
    //插入更改记录
    $result = updatePwd($userId,$password);
        $str = array("code"=>"0","msg"=>"修改成功!","data"=>'{}');
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
}*/

//修改密码
function api_getPwd(){
    $userid=$_REQUEST['userId'];
    $oldpwd=$_REQUEST['oldpwd'];
    $newpwd=$_REQUEST['newpwd'];
    error_log('收到传送参数->>userId'.$userid.'||oldpwd->>'.$oldpwd.'||newpwd->>'.$newpwd);
    if (empty($userid) || empty($oldpwd) || empty($newpwd)){
        $str = array("code"=>"1","msg"=>"参数错误!","data"=>"{}");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        return;
    }
    $result=getPwd($userid);
    if ($oldpwd == $result['password']){
        updatePwd($userid,$newpwd);
        $str = array("code"=>"0","msg"=>"修改成功!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $str = array("code"=>"1","msg"=>"原密码错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }

}
//头像上传
function api_uploadPhoto(){
    $fileNames = $_REQUEST['info'];
    $names = '';
    if (empty($fileNames)){
        //为空
        $str = array("code"=>"0","msg"=>"参数为空");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }else{
        //不为空,获取到名称
        $names = array_diff(explode(',',$fileNames),['']);
    }
    //遍历
    $filePaths = array();
    foreach ($names as $name) {
        $fileData = $_FILES[$name];
        $file_name = $fileData['name'];
        $file_name = date("Y-m-d",time()).time().'_'.$file_name;
        $datetime = date("Y-m-d",time());
        $newFile = 'files/'.$file_name;
        //此函数会覆盖同名文件
        move_uploaded_file($fileData['tmp_name'],$newFile);
        //插入数据库文件表
        $sql = "insert into enclosure values(null,'".$newFile."','".$fileData['name']."','".$datetime."')";
        $result = $GLOBALS['DB']->query($sql);
        $fileid =  $result->insertID();

        $file_id = array();
        $sql = "select id from enclosure where id=".$fileid;
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $file_id = $res;
        }
        $filePaths[] = $file_id;
    }

    $str = array("code"=>"0","msg"=>"上传成功","data"=>$filePaths);
    echo json_encode($str,JSON_UNESCAPED_UNICODE);
}
//更新用户资料
function api_updateProfile(){
    $userId =  $_REQUEST['userId'];
    $work =  $_REQUEST['work'];
    $contact_way =  $_REQUEST['contact_way'];
    $photo_url =  $_REQUEST['photo_url'];

    if (empty($password) || empty($userId)){
        $str = array("code"=>"1","msg"=>"参数错误!","data"=>"{}");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        return;
    }
    //插入更改记录
    $result = updatePwd($userId,$work,$contact_way,$photo_url);
    $str = array("code"=>"0","msg"=>"修改成功!","data"=>'{}');
    echo json_encode($str,JSON_UNESCAPED_UNICODE);
}
//提交反馈
function api_commitFeedback(){
    $userid = $_REQUEST['userId'];
    $proposalId = $_REQUEST['proposalId'];
    $isManyi = $_REQUEST['isManyi'];
    $jutijianyi = $_REQUEST['jutijianyi'];

    $wanjie = false;
    switch ($isManyi){
        case 1:
            //满意 ->> 4办理中
            $sql = "update proposal set state='4' where id=".$proposalId;
            $result = $GLOBALS['DB']->query($sql);
            if ($result){
                $result = updateRecord($proposalId,$userid,'9',$jutijianyi);
                if ($result){
                    $str = array("code"=>"0","msg"=>"反馈成功!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                    $wanjie = true;
                }else{
                    $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }
            }else{
                $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
            break;
        case 2:
            //基本满意 ->> 4办理中
            $sql = "update proposal set state='4' where id=".$proposalId;
            $result = $GLOBALS['DB']->query($sql);
            if ($result){
                $result = updateRecord($proposalId,$userid,'5',$jutijianyi);
                if ($result){
                    $str = array("code"=>"0","msg"=>"反馈成功!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                    $wanjie = true;
                }else{
                    $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }
            }else{
                $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
            break;
        case 3:
            //不满意 ->> 4办理中
            $sql = "update proposal set state='4' where id=".$proposalId;
            $result = $GLOBALS['DB']->query($sql);
            if ($result){
                $result = updateRecord($proposalId,$userid,'10',$jutijianyi);
                if ($result){
                    $str = array("code"=>"0","msg"=>"反馈成功!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                    $wanjie = false;
                }else{
                    $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
                    echo json_encode($str,JSON_UNESCAPED_UNICODE);
                }
            }else{
                $str = array("code"=>"1","msg"=>"提交失败!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
            break;
    }

    if ($wanjie){
        $proposalData = getProposalInfo($proposalId);
        $message = "您的《".$proposalData['anyou']."》提案已办结!";
        $action = 'yiban';
        sendTask($message,$proposalData['userid'],$proposalId,$action,2,0);
    }

}

/**
 * {
 * "role":"123",
 * "description":"",
 * "homepage":1,
 * "myproposal":1,
 * "createproposal":1,
 * "daifankuiproposal":1,
 * "shenchaproposal":1,
 * "jiaobanproposal":1,
 * "banliproposal":1,
 * "yibanproposal":1,
 * "suoyouproposal":1,
 * "weiyuaninfo":1,
 * "message":1,
 * "manager":1
 * }
 */

//创建用户组
function api_createUserGroup(){
    if (empty($_REQUEST['json']) || empty($_REQUEST['userid'])){
        $str = array("code"=>"1","msg"=>"JSON或用户不能为空!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }else{
        $json =  $_REQUEST['json'];
        $userid = $_REQUEST['userid'];
    }

    $userinfo = getUserInfo($userid);
    if (empty($userinfo)){
        $str = array("code"=>"1","msg"=>"用户信息错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    //$json = '{"role":"123","description":"","homepage":1,"myproposal":1,"createproposal":1,"daifankuiproposal":1,"shenchaproposal":1,"jiaobanproposal":1,"banliproposal":1,"yibanproposal":1,"suoyouproposal":1,"weiyuaninfo":1,"message":1,"manager":1}';
    $data = json_decode($json,JSON_UNESCAPED_UNICODE);
    $keys = array_keys($data);
    foreach ($keys as $value){
       if (empty($data[$value])){
           $str = array("code"=>"1","msg"=>"参数错误!","data"=>"");
           echo json_encode($str,JSON_UNESCAPED_UNICODE);
           exit();
       }
    }
    $createtime = date("Y-m-d",time());
    $createuser = $userinfo['username'];

    $sql = "insert into usergroup values(null,'".$data[$keys[0]]."','".$data[$keys[1]]."',".$data[$keys[2]].",".$data[$keys[3]].",".$data[$keys[4]].",".$data[$keys[5]].",".$data[$keys[6]].",".$data[$keys[7]].",".$data[$keys[8]].",".$data[$keys[9]].",".$data[$keys[10]].",".$data[$keys[11]].",".$data[$keys[12]].",".$data[$keys[13]].",'".$createtime."','".$createuser."','".$userid."')";
    $result = $GLOBALS['DB']->query($sql);
    if ($result){
        $str = array("code"=>"0","msg"=>"创建成功!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $str = array("code"=>"1","msg"=>"创建失败!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//更新用户组
function api_updateUserGroup(){
    if (empty($_REQUEST['json']) || empty($_REQUEST['userid']) || empty($_REQUEST['groupid'])){
        $str = array("code"=>"1","msg"=>"JSON或用户不能为空!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }else{
        $json =  $_REQUEST['json'];
        $userid = $_REQUEST['userid'];
        $groupid = $_REQUEST['groupid'];
    }

    $userinfo = getUserInfo($userid);
    if (empty($userinfo)){
        $str = array("code"=>"1","msg"=>"用户信息错误!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
        exit();
    }

    $data = json_decode($json,JSON_UNESCAPED_UNICODE);
    $keys = array_keys($data);
    foreach ($keys as $value){
        if (!isset($data[$value])){
            $str = array("code"=>"1","msg"=>"参数错误!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
            exit();
        }
    }
    $sql = "update usergroup set role='".$data[$keys[0]]."',description='".$data[$keys[1]]."',homepage=".$data[$keys[2]].",myproposal=".$data[$keys[3]].",createproposal=".$data[$keys[4]].",daifankuiproposal=".$data[$keys[5]].",shenchaproposal=".$data[$keys[6]].",jiaobanproposal=".$data[$keys[7]].",banliproposal=".$data[$keys[8]].",yibanproposal=".$data[$keys[9]].",suoyouproposal=".$data[$keys[10]].",weiyuaninfo=".$data[$keys[11]].",message=".$data[$keys[12]].",manager=".$data[$keys[13]]." where id=".$groupid."";
    $result = $GLOBALS['DB']->query($sql);
    if ($result){
        $str = array("code"=>"0","msg"=>"更新成功!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $str = array("code"=>"1","msg"=>"更新失败!","data"=>"");
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//获取用户组信息
function api_getUserGroup(){
    if (!empty($_REQUEST['usergroupid'])){
        $data = getUserGroupToId($_REQUEST['usergroupid']);
        $str = array("code"=>"0","msg"=>"获取成功!","data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

/**
 *   id 主键用户id
 *   username 用户名
 *   password 密码
 *   role 角色(1:超级管理员2:政协委员3:提案委员会4:交办单位 5:办理单位)
 *   photourl 头像地址
 *   realname 真实姓名
 *   sex 性别 (1:男2:女3:保密)
 *   session 届次
 *   age 年龄
 *   party 党派团体
 *   work 工作单位
 *   phone 电话号码
 *   street 所属街道工委
 *   createtime 创建时间
 */

//创建用户
function api_createUser(){
    if (!isset($_REQUEST['hashcode'])){
        if (isset($_REQUEST['json'])){
            $json = $_REQUEST['json'];
            $time = date("Y-m-d",time());
            $data = json_decode($json,JSON_UNESCAPED_UNICODE);


            $userData = array();
            //判断是否有相同用户(唯一键手机号码)
            $sql = "select * from user where phone='".$data['phone']."'";
            $result = $GLOBALS['DB']->query($sql);
            while($res=$result->fetch()) {
                $userData = $res;
            }

            if (!empty($userData)){
                $str = array("code"=>"0","msg"=>"创建失败,此手机号码已注册!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
                exit();
            }

            $groupName = getAllUserGroup();
            $lastname = $data['suoshujuese'];

            foreach ($groupName as $value){
                $value['role'] === $data['suoshujuese']? $data['suoshujuese'] = $value['id']:'';
            }

            if ($lastname === $data['suoshujuese']){
                $str = array("code"=>"0","msg"=>"用户组错误!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
                exit();
            }

            $sql = "insert into user value(null,
                                            '".$data['dengluming']."',
                                            '".$data['denglumima']."',
                                            '".$data['suoshujuese']."',
                                            '',
                                            '".$data['xingming']."',
                                            '".$data['xingbie']."',
                                            '".$data['jieci']."',
                                            '".$data['nianling']."',
                                            '".$data['dangpai']."',
                                            '".$data['gongzuodanwei']."',
                                            '".$data['phone']."',
                                            '".$data['jiedaogongwei']."',
                                            '".$time."',
                                            '".$data['shifouqiyong']."')";
            $result = $GLOBALS['DB']->query($sql);
            if ($result){
                $str = array("code"=>"0","msg"=>"创建成功!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }else{
                $str = array("code"=>"0","msg"=>"创建失败!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }
    }
}

//更新用户
function api_updateUser(){
    if (!isset($_REQUEST['hashcode'])){
        if (isset($_REQUEST['json'])){
            $json = $_REQUEST['json'];
            $data = json_decode($json,JSON_UNESCAPED_UNICODE);
            $group = getAllUserGroup();

            foreach ($group as $value){
                $value['role'] == $data['suoshujuese']? $data['suoshujuese'] = $value['id']:'';
            }

            $sql = "update user set username='".$data['dengluming']."',
                                    password='".$data['denglumima']."',
                                    role='".$data['suoshujuese']."',
                                    realname='".$data['xingming']."',
                                    sex='".$data['xingbie']."',
                                    session='".$data['jieci']."',
                                    age='".$data['nianling']."',
                                    party='".$data['dangpai']."',
                                    work='".$data['gongzuodanwei']."',
                                    phone='".$data['phone']."',
                                    street='".$data['jiedaogongwei']."',
                                    enable='".$data['shifouqiyong']."' where id=".$data['id'];
            $result = $GLOBALS['DB']->query($sql);

            if ($result){
                $str = array("code"=>"0","msg"=>"更新成功!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }else{
                $str = array("code"=>"0","msg"=>"更新失败!","data"=>"");
                echo json_encode($str,JSON_UNESCAPED_UNICODE);
            }
        }
    }
}

//获取任务总数
function api_getTaskCount(){
    if (!isset($_REQUEST['hashcode'])){
        $data = array();
        $sql = "select sum(isLook=2 and taskType=1) as announcementSize,sum(isLook=2 and taskType=2) as taskSize,sum(isLook=2 and taskType=3) as chatSize,sum(isLook=2 and taskType=4) as groupSize from task where userid=".$_SESSION['USERID'];
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $data = $res;
        }
        empty($data['announcementSize']) == false ? '':$data['announcementSize']=0;
        empty($data['taskSize']) == false ? '':$data['taskSize']=0;
        empty($data['chatSize']) == false ? '':$data['chatSize']=0;
        empty($data['groupSize']) == false ? '':$data['groupSize']=0;

        $ansize = array();
        $sql = "select count(*) as num from task where taskType=1 and checkid not like '%".$_SESSION['USERID']."%'";
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $ansize = $res;
        }

        $data['announcementSize'] = $ansize['num'];

        $data['all'] = $data['announcementSize']+$data['taskSize']+$data['chatSize']+$data['groupSize'];
        $str = array("code"=>"0","msg"=>"获取成功!","size"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}


//获取任务列表
function api_getTaskList(){
    if (!isset($_REQUEST['hashcode'])) {
        if (!isset($_REQUEST['curentPage']) || !isset($_REQUEST['mod'])) {
            $str = array("code"=>"0","msg"=>"当前页参数必填!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
            exit();
        }else{
            $curentPage = $_REQUEST['curentPage'];
            $mod = $_REQUEST['mod'];
        }
        $page = $curentPage-1;
        $perpage = 7;
        $data = array();

        switch ($mod){
            case 1://全部
                $sql = "select * from task where userid in (".$_SESSION['USERID'].") or groupid in (select role from user where id in (".$_SESSION['USERID'].")) or taskType=1 order by tasktime desc limit ".$page*$perpage.",".$perpage;
                $countsql = "select count(*) as num from task where userid in (".$_SESSION['USERID'].") or groupid in (select role from user where id in (".$_SESSION['USERID'].")) or taskType=1";
                break;
            case 2://公告
                $sql = "select * from task where taskType in (".($mod-1).") order by tasktime desc limit ".$page*$perpage.",".$perpage;
                $countsql = "select count(*) as num from task where taskType in (".($mod-1).")";
                break;
            case 3://任务
                $sql = "select * from task where userid in (".$_SESSION['USERID'].") and taskType in (".($mod-1).") or groupid in (select role from user where id in (".$_SESSION['USERID'].")) and taskType in (".($mod-1).") order by tasktime desc limit ".$page*$perpage.",".$perpage;
                $countsql = "select count(*) as num from task where userid in (".$_SESSION['USERID'].") and taskType in (".($mod-1).") or groupid in (select role from user where id in (".$_SESSION['USERID'].")) and taskType in (".($mod-1).")";
                break;
            case 4://私聊,暂留
                break;
            case 5://群聊,暂留
                break;
        }

        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $data[] = $res;
        }

        $size = array();
        $result = $GLOBALS['DB']->query($countsql);
        while($res=$result->fetch()) {
            $size = $res;
        }

        for($i=0;$i<count($data);$i++){
            if ($data[$i]['taskType']==1){
                $checkids = explode(',',$data[$i]['checkid']);
                $in = in_array($_SESSION['USERID'],$checkids);
                $in? $data[$i]['isLook'] = 1:$data[$i]['isLook'] = 2;
            }
        }

        $str = array("code"=>"0","msg"=>"获取成功!","size"=>$size['num'],"data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//获取最后的N条数据
function api_getTaskListToNum(){
    if (!isset($_REQUEST['hashcode'])) {
        if (isset($_REQUEST['num'])){
            $num = $_REQUEST['num'];
            $data = array();
            $sql = "select * from task where id=".$_SESSION['USERID']." order by id desc limit ".$num;
            $result = $GLOBALS['DB']->query($sql);
            while($res=$result->fetch()) {
                $data[] = $res;
            }
            $str = array("code"=>"0","msg"=>"获取成功!","data"=>$data);
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }else{
            $str = array("code"=>"0","msg"=>"请填写数量!","data"=>"");
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }
}

function api_getNavNum(){
    if (!isset($_REQUEST['hashcode'])) {
        $sql = "select sum(state=1) as shenchaSize,sum(state=3) as jiaobanSize,sum(state=4) as banliSize,sum(state=5) as fankuiSize from proposal";
        $data = array();
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()){
            $data = $res;
        }

        $sql = "select sum(isLook=2) as allSize from task where userid=".$_SESSION['USERID'];
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $size = $res;
        }

        $ansize = array();
        $sql = "select count(*) as num from task where taskType in(1,2) and checkid not like '%".$_SESSION['USERID']."%'";
        $result = $GLOBALS['DB']->query($sql);
        while($res=$result->fetch()) {
            $ansize = $res;
        }
        ($ansize['num'] != 0)? $data['messageCenter'] = $ansize['num']:$data['messageCenter'] = 0;


        empty($data['shenchaSize'])? $data['shenchaSize']=0:'';
        empty($data['jiaobanSize'])? $data['jiaobanSize']=0:'';
        empty($data['banliSize'])? $data['banliSize']=0:'';
        empty($data['fankuiSize'])? $data['fankuiSize']=0:'';
        empty($size['allSize']) == false? $data['allSize'] = $size['allSize']:$data['allSize']=0;
        $str = array("code"=>"0","msg"=>"获取成功!","data"=>$data);
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

//获取委员信息任务列表
function api_getweiyuanList(){
    $curentPage = $_REQUEST['curentPage'];
    $jieci = $_REQUEST['jieci'];
    $page = $curentPage-1;
    $perpage = 10;
    $data = array();
    $count = array();

    if (empty($jieci)){
        $sql = "select * from user where role in(2,3) order by id desc limit ".$page*$perpage.",".$perpage;
        $countsql = "select count(*) as num from user where role in(2,3)";
    }else{
        $sql = "select * from user where role in(2,3) and session=".$jieci." order by id desc limit ".$page*$perpage.",".$perpage;
        $countsql = "select count(*) as num from user where role in(2,3) and session=".$jieci;
    }

    $result = $GLOBALS['DB']->query($sql);
    while($res=$result->fetch()) {
        $data[] = $res;
    }

    $result = $GLOBALS['DB']->query($countsql);
    while($res=$result->fetch()) {
        $count = $res;
    }

    $str = array("code"=>"0","msg"=>"获取成功!","size"=>count($count['num']),"data"=>$data);
    echo json_encode($str,JSON_UNESCAPED_UNICODE);
}

/**
 * 发布公告
 */
function api_sendAnnouncement(){
    if(empty($_REQUEST['hashcode'])){
        $content = $_REQUEST['content'];
        $title = $_REQUEST['title'];
        $date = date("Y-m-d H:i:s",time());
        if (!empty($_REQUEST['fileid'])){
            $enclosureid = $_REQUEST['fileid'];
            //有文件
            $sql = "insert into task value(null,'".$date."','".$content."',2,0,".$_SESSION['USERID'].",0,1,'xinxi',0,'".$title."','".$enclosureid."','')";
            $GLOBALS['DB']->query($sql);
        }else{
            $sql = "insert into task value(null,'".$date."','".$content."',2,0,".$_SESSION['USERID'].",0,1,'xinxi',0,'".$title."','','')";
            $GLOBALS['DB']->query($sql);
        }
        $str = array("code"=>"0","msg"=>"发布成功!","data"=>'');
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 修改个人资料
 */
function api_modifyUserInfo(){
    if (empty($_REQUEST['xingming']) || empty($_REQUEST['nianling']) || empty($_REQUEST['dangpai']) || empty($_REQUEST['gongzuo']) || empty($_REQUEST['phone'])){
        $str = array("code"=>"1","msg"=>"参数不能为空!","data"=>'');
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }else{
        $sql = "update user set realname='".$_REQUEST['xingming']."',age='".$_REQUEST['nianling']."',party='".$_REQUEST['dangpai']."',work='".$_REQUEST['gongzuo']."',phone='".$_REQUEST['phone']."' where id=".$_SESSION['USERID'];
        $result = $GLOBALS['DB']->query($sql);
        if ($result){
            $str = array("code"=>"0","msg"=>"修改成功!","data"=>'');
            echo json_encode($str,JSON_UNESCAPED_UNICODE);
        }
    }
}

/**
 *  id 主键用户id
    username 用户名
    password 密码
    role 角色(1:超级管理员2:政协委员3:提案委员会4:交办单位 5:办理单位)
    photourl 头像地址
    realname 真实姓名
    sex 性别 (1:男2:女3:保密)
    session 届次
    age 年龄
    party 党派团体
    work 工作单位
    phone 电话号码
    street 所属街道工委
    createtime 创建时间
 */



